const requestJson = function(url,content={}) {
    if(url.startsWith("/")){
        url="http://127.0.0.1:19988"+url;
    }
    const promise = new Promise(function(resolve, reject){
        const handler = function() {
            if (this.readyState !== 4) {
                return;
            }
            if (this.status === 200) {
                resolve(this.response);
            } else {
                reject(new Error(this.statusText));
            }
        };
        const client = new XMLHttpRequest();
        client.open("POST", url);
        client.onreadystatechange = handler;
        client.responseType = "json";
        client.setRequestHeader("Accept", "application/json");
        client.setRequestHeader("Content-Type","application/json")
        client.send(JSON.stringify(content));

    });
    return promise;
};

function syntaxHighlight(json) {
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}



let myApp = new Vue({
    el: '#app',
    data: function () {
        return {
            contextMenuVisible: false,
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            data: [],
            defaultProps:{
                label:'name'
            },
            contextMenuTarget:null,
            contextMenuElement:null,
            tableData:[],
        };
    },
    methods: {
        //左键点击
        handleNodeClick(data) {
            console.log(data);
            this.tableData=data.param;
        },
        startNode(){
            let data=this.contextMenuElement.data;
            let serverName=data.name;
            console.log('启动');
            requestJson("/ui/startServer",{serverName:serverName}).then(item=>{
                console.log(item);
                console.log('启动返回');
            })
        },
        stopNode(){
            let data=this.contextMenuElement.data;
            let serverName=data.name;
            console.log('停止');
            requestJson("/ui/stopServer",{serverName:serverName}).then(item=>{
                console.log(item);
                console.log('停止返回');
            })

        },
        //右键点击菜单显示
        handleContextMenu(event,data,element) {
            let currentTarget=event.currentTarget;
            this.contextMenuTarget=currentTarget;
            this.contextMenuElement=element;
            if(data.type!=='SERVER'){
                return;
            }
            this.contextMenuVisible=true;
            let {x,y}=this.getXY(currentTarget);
            let contextMenu=this.$refs.contextMenu;
            if(x==0){
                x=100;
            }
            [contextMenu.x,contextMenu.y]=[x,y];
            contextMenu.layout();
            console.log([contextMenu.x,contextMenu.y,x,y]);
            console.log(arguments);
        },
        handleNodeChange() {
            console.log(arguments)
        },

        getXY(obj) {
            let x = 0, y = 0;
            if (obj.getBoundingClientRect) {
                let box = obj.getBoundingClientRect();
                let D = document.documentElement;
                x = box.left + Math.max(D.scrollLeft, document.body.scrollLeft) - D.clientLeft;
                y = box.top + Math.max(D.scrollTop, document.body.scrollTop) - D.clientTop
            } else {
                for (; obj != document.body; x += obj.offsetLeft, y += obj.offsetTop, obj = obj.offsetParent) {
                }
            }
            return {
                x: x,
                y: y
            }
        },
        loadData() {
            requestJson("/ui/getApplication").then(item=>{
                console.log(item);
                this.data=item;
            })
            this.tableData=[{
                dataKey:'2020',
                dataVal:'ss',
            }]
        }
    },
    mounted() {
        // vue-context-menu 需要传入一个触发右键事件的元素，等页面 dom 渲染完毕后才可获取
        this.contextMenuTarget = document.querySelector('#el-tree');
        // 获取所有的 treeitem，循环监听右键事件
        const tree = document.querySelectorAll('#el-tree [role="treeitem"]');
        tree.forEach(i => {
            i.addEventListener('contextmenu', event => {
                // 如果右键了，则模拟点击这个treeitem
                event.target.click()
            })
        });
        this.loadData()
    },
});

let ws = new WebSocket('ws://localhost:19988/webSocket')
// 连接成功就会执行回调函数
ws.onopen = function (params) {
    console.log('客户端连接成功')
    // 向服务器发送消息
    ws.send('hello')
}
// 必须用属性的方式监听事件，监听函数的参数是事件对象
ws.onmessage = function (e) {
    console.log('收到服务器响应', e.data)
    let receiveMsg=JSON.parse(e.data);
    myApp.data=receiveMsg;
}
ws.onclose = function(evt) {
    console.log("Connection closed.");
};